package nsh.cl.nd.khtn.mazedash.baseclasses;

import nsh.cl.nd.khtn.mazedash.GameConstant;
import nsh.cl.nd.khtn.mazedash.RootGameActivity;

import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.FadeOutModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.util.modifier.IModifier;

public abstract class BaseFadeInScene extends Scene implements IEntityModifierListener {
	abstract protected void loadSceneResources();

	private Sprite background;

	@Override
	public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
	}

	@Override
	public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
		RootGameActivity.getInstance().runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				detachChild(background);
				onScreenReady();
			}
		});
	}

	protected void onScreenReady() {
	}

	public void loadResources() {
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		BitmapTextureAtlas tAtlas = new BitmapTextureAtlas(RootGameActivity.getInstance().getTextureManager(),
				GameConstant.TEXTUREATLAS_MAX_WIDTH, GameConstant.TEXTUREATLAS_MAX_HEIGHT);
		TextureRegion tRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(tAtlas,
				RootGameActivity.getInstance(), GameConstant.PATH_MASK_BLACK, 0, 0);
		tAtlas.load();
		background = new Sprite(0, 0, tRegion, RootGameActivity.getInstance().getVertexBufferObjectManager());
		loadSceneResources();
	}

	public void animateIn() {
		resetScreen();
		fadeIn(this);
	}

	protected void resetScreen() {
	}

	public void fadeIn(IEntityModifierListener modifierListener) {
		background.clearEntityModifiers();
		background.setAlpha(1.0f);
		background.registerEntityModifier(new FadeOutModifier(0.5f, modifierListener));
		if (background.hasParent()) {
			RootGameActivity.getInstance().runOnUpdateThread(new Runnable() {
				@Override
				public void run() {
					detachChild(background);
					attachChild(background);
				}
			});
		} else {
			attachChild(background);
		}
	}
}